from django.shortcuts import render

import json

from django.core.exceptions import ObjectDoesNotExist

from api.utils import success_response_with_data, failed_response_with_data, list_response
from api.models import Material, RecordTts, RecordVideo
from api.serializers import MaterialSerializer, RecordTtsSerializer, RecordVideoSerializer

from rest_framework import viewsets
from drf_yasg2.utils import swagger_auto_schema
from drf_yasg2 import openapi
from rest_framework.decorators import action
from django.db.models import Q
from django.db.models import Count

from api.mylogger import logger


# Create your views here.


class DashboardViewSet(viewsets.ViewSet):
    @swagger_auto_schema(operation_id='资源数量查询', tags=['dashboard'],
                         method='POST',
                         request_body=openapi.Schema(
                             type=openapi.TYPE_OBJECT,
                             properties={
                                 "material_type": openapi.Schema(type=openapi.TYPE_STRING, description="material_type"),
                                 "material_subtype": openapi.Schema(type=openapi.TYPE_STRING, description="material_subtype"),
                             },
                         )
                         )
    @action(methods=['POST'], detail=False)
    def count_material(self, request):
        data = json.loads(request.body.decode('utf8'))
        material_type = data.get('material_type', '')
        material_subtype = data.get('material_subtype', '')
        try:
            objects = Material.objects.filter(status=True)
            if material_type != '':
                objects = objects.filter(material_type=material_type)
            if material_subtype != '':
                objects = objects.filter(material_subtype=material_subtype)
            rows = objects.all()
            total = rows.count()
            logger.debug(f"rows count is {total} sql: {rows.query}")
            resdata= {
                'material_type': material_type,
                'count': total
            }
            return success_response_with_data(resdata, msg='查询OK')
        except ObjectDoesNotExist:
            logger.debug("没有发现记录")
            resdata = {
                'material_type': material_type,
                'count': 0
            }
            return success_response_with_data(resdata, msg='查询OK')

    @swagger_auto_schema(operation_id='TTS语音数量查询', tags=['dashboard'],
                         method='POST',
                         request_body=openapi.Schema(
                             type=openapi.TYPE_OBJECT,
                             properties={
                                 "material_type": openapi.Schema(type=openapi.TYPE_STRING, description="material_type"),
                             },
                         )
                         )
    @action(methods=['POST'], detail=False)
    def count_tts(self, request):
        data = json.loads(request.body.decode('utf8'))
        material_type = data.get('material_type', '')

        try:
            objects = RecordTts.objects
            objects = objects.filter(Q(material_type=material_type) & Q(status=True) )
            rows = objects.all()
            total = rows.count()
            logger.debug(f"rows count is {total} sql: {rows.query}")
            resdata= {
                'material_type': material_type,
                'count': total
            }
            return success_response_with_data(resdata, msg='查询OK')
        except ObjectDoesNotExist:
            logger.debug("没有发现记录")
            resdata = {
                'material_type': material_type,
                'count': 0
            }
            return success_response_with_data(resdata, msg='查询OK')


    @swagger_auto_schema(operation_id='AI视频数量查询', tags=['dashboard'],
                         method='POST',
                         request_body=openapi.Schema(
                             type=openapi.TYPE_OBJECT,
                             properties={
                                 "material_type": openapi.Schema(type=openapi.TYPE_STRING, description="material_type"),
                             },
                         )
                         )
    @action(methods=['POST'], detail=False)
    def count_aivideo(self, request):
        data = json.loads(request.body.decode('utf8'))
        material_type = data.get('material_type', '')

        try:
            objects = RecordVideo.objects
            objects = objects.filter(Q(material_type=material_type) & Q(status=True) )
            rows = objects.all()
            total = rows.count()
            logger.debug(f"rows count is {total} sql: {rows.query}")
            resdata= {
                'material_type': material_type,
                'count': total
            }
            return success_response_with_data(resdata, msg='查询OK')
        except ObjectDoesNotExist:
            logger.debug("没有发现记录")
            resdata = {
                'material_type': material_type,
                'count': 0
            }
            return success_response_with_data(resdata, msg='查询OK')


    @swagger_auto_schema(operation_id='资源分组数量查询', tags=['dashboard'],
                         method='POST',
                         request_body=openapi.Schema(
                             type=openapi.TYPE_OBJECT,
                             properties={
                             },
                         )
                         )
    @action(methods=['POST'], detail=False)
    def material_group_by_type(self, request):
        try:
            # objects = Material.objects.filter(status=True)
            # objects = objects.filter(status=True)
            rows = Material.objects.annotate(mcount=Count('material_type')).values('material_type', 'mcount')
            print('rows is ', rows)

            for row in rows:
                print('row is ',row)

            return success_response_with_data(MaterialSerializer(rows, many=True).data, msg='查询OK')
        except ObjectDoesNotExist:
            logger.debug("没有发现记录")
            return success_response_with_data({}, msg='没有发现记录')